// Package user 存放用户 Model 相关逻辑
package models

import (
	"books/pkg/database"
	"time"
)

// Loan 模型
type Loan struct {
	BaseModel

	BookID           uint64 `json:"book_id"`
	Book             *Book  `json:"book"`
	User             *User  `json:"user"`
	UserID           uint64 `json:"user_id"`
	ReturnDate       uint64 `json:"return_date"`
	ShouldReturnDate uint64 `json:"should_return_date"`
	IsReturn         int    `json:"is_return"`

	CommonTimestampsField
}

func GetLoans(name, user string, is_return int) ([]Loan, error) {
	var loans []Loan
	var userIds []uint64
	var bookIds []uint64

	if user != "" {
		users, err := GetUsers(user, "")
		if err != nil {
			return nil, err
		}
		// 如果users长度为0，则直接返回空
		if len(users) == 0 {
			return nil, nil
		}
		// 遍历users，获取user_id

		for _, v := range users {
			userIds = append(userIds, v.ID)
		}
	}

	if name != "" {
		books, err := GetBooks(name, "", 0, false)
		if err != nil {
			return nil, err
		}
		// 如果books长度为0，则直接返回空
		if len(books) == 0 {
			return nil, nil
		}
		// 遍历books，获取book_id
		for _, v := range books {
			bookIds = append(bookIds, v.ID)
		}
	}

	db := database.DB.Model(Loan{}).Preload("Book").Preload("User")

	if user != "" {
		db = db.Where("user_id in ?", userIds)
	}
	if name != "" {
		db = db.Where("book_id in ?", bookIds)
	}
	if is_return != 99 {
		db = db.Where("is_return = ?", is_return)
	}

	err := db.Order("id desc").Find(&loans).Error
	return loans, err
}

func GetLoan(id uint64) (*Loan, error) {
	loan := &Loan{}
	err := database.DB.Model(Loan{}).Where("id = ?", id).First(&loan).Error
	return loan, err
}

func Return(id uint64) error {
	loan := &Loan{
		ReturnDate: uint64(time.Now().Unix()),
		IsReturn:   1,
	}
	err := database.DB.Model(Loan{}).Where("id = ?", id).Updates(loan).Error

	return err
}

func (t *Loan) CreateLoan() error {
	err := database.DB.Create(&t).Error
	return err
}
